package com.weex.app.extend;

import android.content.Context;
import android.support.annotation.Nullable;

import com.taobao.weex.bridge.JSCallback;
import com.tencent.wcdb.database.SQLiteDatabase;
import com.tencent.wcdb.database.SQLiteOpenHelper;


public class WxSQLiteOpenHelper extends SQLiteOpenHelper{
    protected SQLiteDatabase db;
    private JSCallback _onCreate;
    private JSCallback _onUpgrade;
    private static final int SLEEP_TIME_MS = 30;

    public WxSQLiteOpenHelper(
            @Nullable Context context,
            @Nullable String name,
            int version,
            JSCallback onCreate,
            JSCallback onUpgrade
    ) {
        super(context, name, null, version);
        setWriteAheadLoggingEnabled(true);

        db = null;
        _onCreate=onCreate;
        _onUpgrade=onUpgrade;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        this.db = db;

        if(_onCreate!=null) {
            _onCreate.invoke(null);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        this.db = db;

        if(_onUpgrade!=null) {
            _onUpgrade.invoke(new Object[]{oldVersion, newVersion});
        }
    }

    synchronized void open() {
        if (db != null && db.isOpen()) {
            return;
        }
        db = getWritableDatabase();
    }

}
